﻿<?php
class sql {

	private static $_instance = null;
	private static $_query = null;
	private static $_nbr_queries = 0;
	private $pdo = null;

	const SGBDR = 'mysql';
	const HOST = 'localhost';
	const USER = 'root';
	const MDP = '';
	const BDD = 'thiebthieb';
        //const BDD = 'pagination';
	

	private function __construct($sgbdr, $host, $user, $mdp, $bdd) {
		$this->pdo = new PDO($sgbdr .':host='. $host .';dbname='. $bdd, $user, $mdp);
	}
	public static function connect($sgbdr = self::SGBDR, $host = self::HOST, $user = self::USER, $mdp = self::MDP, $bdd = self::BDD) {
		if(is_null(self::$_instance)) {
			self::$_instance = new sql($sgbdr, $host, $user, $mdp, $bdd);
		}
		return self::$_instance;
	}
	private function increment() { /* Incrémente le compteur de requetes effectuées. */
		++self::$_nbr_queries;
		return TRUE;
	}
	public function getNbr_queries() { /* Récupère le compteur de requêtes effectuées */
		return self::$_nbr_queries;
	}
	public function query($query, $mode = null) {
              
		if(preg_match('#^(SELECT) #i', $query)) {  //necessite methode query()
			if(!is_null(self::$_query)) //si l'attribut requete n'est pas vide, c'est qu'il faut fermer son curseur.
				self::$_query->closeCursor();
			$query = $this->pdo->query($query);
                                               
			if(!is_null($mode))
				$query->setFetchMode($mode);
			self::$_query = &$query; //on met l'attribut requete a jour
			
                        $this->increment(); 
			return $query;
		}
		else { //necessite methode exec()
			$this->increment();
			return $this->pdo->exec($query);
		}
	}
        
        
	public function fetch_assoc(PDOStatement $query) { /* mysql_fetch_assoc(); */
		return $query->fetch(PDO::FETCH_ASSOC);
	}
	public function fetch_array(PDOStatement $query) { /* mysql_fetch_array(); */
		return $query->fetch(PDO::FETCH_BOTH);
	}
     
	public function num_rows(PDOStatement $query) { /* mysql_num_rows(); */
		return $query->rowCount();
	}
	public function real_escape_string($char) { /* mysql_real_escape_string(); */
		$escape = $this->pdo->quote($char, PDO::PARAM_STR);
		return substr($escape, 1, -1); //substr pour enlever les guillemets automatiques.
	}
	public function insert_id() { /* mysql_insert_id(); */
		return $this->pdo->lastInsertId();
	}
	public function error() { /* mysql_error(); */
		return $this->pdo->errorInfo();
	}
	public function __call($name, $args)
	{
    return call_user_func_array(array( $this, $name ), $args);
	}
}
/* Test de la classe 
$sql = sql::connect();
$requete = $sql->query('SELECT * FROM categorie');
while($resultat = $sql->fetch_array($requete)) {
	echo $resultat['id_categorie'] .'<br />';
}
echo $sql->real_escape_string('Le site du Zéro m\'a tout appris');
// tout fonctionne sauf la ligne suivante :
echo $sql->num_rows($requete);
*/
?>